package com.homework.news

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.StrictMode
import android.widget.TextView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL


import android.text.Html
import android.util.Log
import android.webkit.WebView
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements


class NewsDetailActivity : AppCompatActivity() {
    var title: TextView? = null
    var author: TextView? = null
    var date: TextView? = null
    var content: TextView? = null
    var baseUrl = "http://v.juhe.cn/toutiao/content?uniquekey="
    var key = "&key=fb8892fddef5be07d42d4f920ad76a87"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_news_detail)
        if (Build.VERSION.SDK_INT > 9) {
            val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
            StrictMode.setThreadPolicy(policy)
        }
        getView()
        var news: News = intent.getSerializableExtra("news") as News
        var responseData = getHttpResult(news.uniquekey)
        var jsonArray = JSONObject(responseData);
        var result = jsonArray.get("result").toString()
        //Log.i("result", result)
        var data = JSONObject(result).get("content").toString()
        title?.text = news.title
        author?.text = news.author_name
        date?.text = news.date
        var htmlText = getNewContent(data)
        content?.text = Html.fromHtml(htmlText, MImageGetter(content, this), null)
    }

    private fun getView(){
        title = findViewById(R.id.title)
        author = findViewById(R.id.author)
        date = findViewById(R.id.date)
        content = findViewById(R.id.content)
    }

    private fun getNewContent(htmltext: String): String{

        var doc: Document = Jsoup.parse(htmltext);
        var elements: Elements = doc.getElementsByTag("img");
        for (element in elements) {
            element.attr("width","100%").attr("height","auto");
        }
        Log.d("VACK", doc.toString());
        return doc.toString();
    }

    fun getHttpResult(uniquekey: String?): String? {
        var urlStr = baseUrl + uniquekey + key
        return try {
            val url = URL(urlStr)
            val connect = url.openConnection() as HttpURLConnection
            val input = connect.inputStream
            val `in` = BufferedReader(InputStreamReader(input))
            var line: String? = null
            println(connect.responseCode)
            val sb = StringBuffer()
            while (`in`.readLine().also { line = it } != null) {
                sb.append(line)
            }
            sb.toString()
        } catch (e: Exception) {
            println(e.toString())
            null
        }
    }

    private fun parseJSONWithGSON(jsonData: String): List<News> {
        val gson = Gson()
        val typeOf = object : TypeToken<List<News>>() {}.type
        val newsList = gson.fromJson<List<News>>(jsonData, typeOf)
        println(newsList[1].title)
        return newsList;
    }
}